import { createRouter, createWebHistory } from 'vue-router'
import { userInfoStore } from '@/pinia/userInfo'

const routes = [
  {
    path: '/',
    name: 'home',
    redirect: { name: 'login' }
  },
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "Login" */ '../views/Login.vue')
  },
  {
    path: '/about',
    name: 'about',
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 有token才会获取路由权限
// 分开获取的 如果获取权限时间过长 不应该进行页面的跳转
// 页面刷新之后 动态路由信息丢失问题
router.beforeEach(async (to, from, next) => {
  const userInfo = userInfoStore()
  if (userInfo.tokens) {
    if (!userInfo.sign) {
      await userInfo.setUserAllowedRoutes()
      return next(to.fullPath)
    }
    // 只要token可以成功获取就让其进行跳转
    next()
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
